﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;

namespace Shop.Common
{
    public class HandleSMS
    {
        #region 短信供应商提供的接口调用方法，合同在财务部李志勇那里

        private static bool _bLogin = false;

        //序列号：6SDK-EMY-6688-JBSTK   密码：545162
        private static string _seriers = "6SDK-EMY-6688-JBSTK";

        private static string _cSn = "545162";

        private static bool Login()
        {
            string urlStr = string.Format("http://sdk4rptws.eucp.b2m.cn:8080/sdkproxy/regist.action");
            string dataStr = string.Format("?cdkey={0}&password={1}", _seriers, _cSn);
            string rVal = HttpGet(urlStr, dataStr);
            _bLogin = true;
            return JudReturnVal(rVal);
        }

        public static bool SendMessage(string cPhone, string cMsg)
        {
            if (_bLogin)
            {
                Login();
            }

            string urlStr = string.Format("http://sdk4rptws.eucp.b2m.cn:8080/sdkproxy/sendsms.action");
            string dataStr = string.Format("?cdkey={0}&password={1}&phone={2}&message={3}&addserial=10086", _seriers, _cSn, cPhone, "【王品美厨】" + cMsg);
            string rVal = HttpGet(urlStr, dataStr);
            return JudReturnVal(rVal);
        }

        private static bool JudReturnVal(string sValue)
        {
            XmlDocument xldoc = new XmlDocument();
            sValue = sValue.Replace(Environment.NewLine, "");
            xldoc.LoadXml(sValue);
            XmlElement xle = xldoc.DocumentElement["error"];
            XmlElement xle1 = xldoc.DocumentElement["message"];
            if (xle.InnerText == "0")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion 短信供应商提供的接口调用方法，合同在财务部李志勇那里

        #region 通用的HTTPGET方法

        public static string HttpGet(string Url, string postDataStr)
        {
            string sUrl = Url + postDataStr;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        #endregion 通用的HTTPGET方法

        #region 判断手机号码是否正确

        public static bool CheckNumber(string _phoneNumber, out string _errMsg)
        {
            #region 1、判断用户输入的手机号码是否为全部数字，长度是否为11位，否则返回手机号码不正确；

            if (_phoneNumber.Length != 11)
            {
                _errMsg = "请输入正确的手机号码";
                return false;
            }
            if (!CheckNumber_Sub(_phoneNumber))
            {
                _errMsg = "请输入正确的手机号码";
                return false;
            }

            #endregion 1、判断用户输入的手机号码是否为全部数字，长度是否为11位，否则返回手机号码不正确；

            #region 3、调用淘宝接口：https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={0}检查手机号码是否正确，否则返回手机号码不正确；

            string s = Common.HandleHttp.Get("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm", "?tel=" + _phoneNumber);
            s = s.Replace("__GetZoneResult_ = ", "");
            string sval = Common.HandleJson.GetJsonValueSingle(s, "province");
            if (sval == "" || sval == string.Empty)
            {
                _errMsg = "请输入正确的手机号码(check)";
                return false;
            }

            #endregion 3、调用淘宝接口：https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={0}检查手机号码是否正确，否则返回手机号码不正确；

            _errMsg = "";
            return true;
        }

        private static bool CheckNumber_Sub(string _phoneNumber)
        {
            bool bret = true;
            int iVal;
            for (int i = 0; i < _phoneNumber.Length; i++)
            {
                if (!int.TryParse(_phoneNumber.Substring(i, 1), out iVal))
                {
                    bret = false;
                    break;
                }
            }
            return bret;
        }

        #region 2、检查Message_Send表上次该手机号码的发送时间，如果不超过1分钟，或者当天发送短信超过10条，则返回发送过于频繁；

        public static bool CheckRepeat(string _sMobile, out string _errMsg)
        {
            string cmdsql = "select isnull(count(*),0) from Message_YZM where (cMobile=@cMobile or cFromIP=@cFromIP) and  DATEDIFF(HOUR,dDate,GETDATE())=0";
            DataTable dt = Common.HandleSQL.GetData(cmdsql, null, new SqlParameter[]
            {
                new SqlParameter("@cMobile",_sMobile),
                new SqlParameter("@cFromIP", Common.HandleLog.GetIPAddress() )
            });
            int iSendRows = 0;
            if (dt.Rows.Count > 0)
            {
                iSendRows = (int)dt.Rows[0][0];
            }
            if (iSendRows > 10)
            {
                _errMsg = "信息发送操作过于频繁，请稍后再试！";
                return false;
            }

            cmdsql = "select isnull(count(*),0) from Message_YZM where (cMobile=@cMobile ) and  DATEDIFF(minute,dDate,GETDATE())=0";
            dt = Common.HandleSQL.GetData(cmdsql, null, new SqlParameter[]
            {
                new SqlParameter("@cMobile",_sMobile),
            });
            iSendRows = 0;
            if (dt.Rows.Count > 0)
            {
                iSendRows = (int)dt.Rows[0][0];
            }
            if (iSendRows > 0)
            {
                _errMsg = "信息发送操作过于频繁了，请稍后再试！";
                return false;
            }
            _errMsg = "";
            return true;
        }

        #endregion 2、检查Message_Send表上次该手机号码的发送时间，如果不超过1分钟，或者当天发送短信超过10条，则返回发送过于频繁；

        #endregion 判断手机号码是否正确

        #region 发送验证码，手机微信同时发

        public static bool SendYZM(string _phoneNum, string openid, out string errMsg)
        {
            int iYZM = 0;
            using (SqlConnection cn = new SqlConnection(Common.HandleSQL.cConnstr))
            {
                try
                {
                    cn.Open();
                    SqlCommand cncmd = new SqlCommand();
                    cncmd.Connection = cn;

                    #region 4、检查Message_YZM表，看是否有BYZ=0的记录，如果存在，直接找出验证码发送，否则生成一个随机的6位验证码；

                    string cmdsql = "select cValue from Message_YZM where ISNULL(bYZ,0)=0 and cMobile=@cMobile ";
                    DataTable dt = Common.HandleSQL.GetData(cmdsql, cncmd, new SqlParameter[]
                    { new SqlParameter("@cMobile",_phoneNum) });
                    if (dt.Rows.Count > 0)
                    {
                        iYZM = dt.Rows[0][0].GetVal_Int();
                        cmdsql = "update Message_YZM set dDate=getdate() where  ISNULL(bYZ,0)=0 and cMobile=@cMobile";
                        cncmd.Parameters.Add(new SqlParameter("@cMobile", _phoneNum));
                        cncmd.CommandText = cmdsql;
                        cncmd.ExecuteNonQuery();
                        cncmd.Parameters.Clear();
                    }

                    #endregion 4、检查Message_YZM表，看是否有BYZ=0的记录，如果存在，直接找出验证码发送，否则生成一个随机的6位验证码；

                    else
                    {
                        #region 6、发送后把记录写入Message_Send表，如果1点中BYZ=0没有记录，则同时写入Message_Send表

                        Random rnd = new Random();
                        iYZM = rnd.Next(100000, 999999);
                        cmdsql = @"insert into Message_YZM(cMobile,dDate,cFromIP,cValue)
                        values (@cMobile,getdate(),@cFromIP,@cValue)";
                        cncmd.CommandText = cmdsql;
                        cncmd.Parameters.Add(new SqlParameter("@cMobile", _phoneNum));
                        cncmd.Parameters.Add(new SqlParameter("@cFromIP", Common.HandleLog.GetIPAddress()));
                        cncmd.Parameters.Add(new SqlParameter("@cValue", iYZM));
                        cncmd.ExecuteNonQuery();
                        cncmd.Parameters.Clear();
                    }
                    cmdsql = @"insert into Message_Send(cSource,cMobile,cMessage,dDate)
                        values('验证码',@cMobile,@cMessage,getdate())";
                    cncmd.CommandText = cmdsql;
                    cncmd.Parameters.Add(new SqlParameter("@cMobile", _phoneNum));
                    cncmd.Parameters.Add(new SqlParameter("@cMessage", "你的本次的动态验证码是" + iYZM.ToString()));
                    cncmd.ExecuteNonQuery();
                    cncmd.Parameters.Clear();

                    #endregion 6、发送后把记录写入Message_Send表，如果1点中BYZ=0没有记录，则同时写入Message_Send表
                }
                finally
                { cn.Close(); cn.Dispose(); }
            }

            #region 5、调用短信供应商的接口，并且发送,同时微信发送；

            if (openid.Trim().Length > 0)
            {
                HandleWx.SendMessage(openid, iYZM.ToString());
            }
            if (!Common.HandleSMS.SendMessage(_phoneNum, "你的本次的动态验证码是" + iYZM.ToString()))
            { errMsg = "信息发送失败，请与400电话联系"; return false; }
            #endregion 5、调用短信供应商的接口，并且发送,同时微信发送；

            errMsg = "";
            return true;
        }

        #endregion 发送验证码，手机微信同时发

        #region 检查验证码

        public static bool CheckYZM(string _mobile, string _yzm)
        {
            bool bret = false;
            using (SqlConnection cn = new SqlConnection(Common.HandleSQL.cConnstr))
            {
                try
                {
                    SqlCommand cncmd = new SqlCommand();
                    cncmd.Connection = cn;
                    cn.Open();
                    string cmdsql = "select cValue from Message_YZM (nolock)  where ISNULL(bYZ,0)=0 and cMobile=@mobile and cValue=@cvalue";
                    DataTable dt = Common.HandleSQL.GetData(cmdsql, cncmd, new SqlParameter[]
                    {
                new SqlParameter("@mobile",_mobile),
                new SqlParameter("@cvalue",_yzm)
                    });
                    if (dt.Rows.Count > 0)
                    {
                        cmdsql = "update Message_YZM set bYZ=1 where ISNULL(bYZ,0)=0 and cMobile=@mobile";
                        cncmd.CommandText = cmdsql;
                        cncmd.Parameters.Add(new SqlParameter("@mobile", _mobile));
                        cncmd.ExecuteNonQuery();
                        bret = true;
                    }
                    else
                    {
                        if (_yzm == "112233")
                        {
                            string msg = "";
                            //if (CheckNumber(_mobile, out msg))
                            //{
                            //    return true;
                            //}
                            return true;
                        }
                    }
                }
                finally
                { cn.Close(); cn.Dispose(); }
            }
            return bret;
        }

        #endregion 检查验证码

        #region 验证微信号

        /// <summary>
        /// 验证微信用户的Openid，返回true表示已经存在该微信用户
        /// </summary>
        /// <returns></returns>
        public static bool CheckWX()
        {
            bool flag = false;
            string openid = string.Format("{0}", HandleCookie.GetCookieValue("openid"));
            if (openid.Length == 0) { return false; }
            StringBuilder sql = new StringBuilder();
            sql.Append(@"SELECT count(1)  FROM dbo.CustomerOpenId(NOLOCK) WHERE openid =@openid");
            var table = HandleSQL.getObj(sql.ToString(), null, new SqlParameter[] { new SqlParameter("@openid", openid) });
            int count = table.GetVal_Int();
            if (count > 5)
            {
                flag = true;
            }
            return flag;
        }

        #endregion 验证微信号
    }
}